package com.timer.taskRule.config;

import com.timer.taskRule.entity.Permissions;
import com.timer.taskRule.entity.Role;
import com.timer.taskRule.entity.User;
import com.timer.taskRule.mapper.LoginMapper;
import com.timer.taskRule.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {
	@Autowired
	private LoginService loginService;

	/**
	 * @MethodName doGetAuthorizationInfo
	 * @Description 权限配置类
	 * @Param [principalCollection]
	 * @Return AuthorizationInfo
	 * @Author WangShiLin
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		//获取登录用户名
		String userName = (String) principalCollection.getPrimaryPrincipal();
		//查询用户名称
		List<Role> roleList = loginService.findRoleList(userName);
		//添加角色和权限
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		for (Role role : roleList) {
			//添加角色
			simpleAuthorizationInfo.addRole(role.getRoleName());
			List<Permissions> permissionsList = loginService.findPermissionsList(role.getId());
			//添加权限
			for (Permissions permissions : permissionsList) {
				simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
			}
		}

		return simpleAuthorizationInfo;
	}

	/**
	 * @MethodName doGetAuthenticationInfo
	 * @Description 认证配置类
	 * @Param [authenticationToken]
	 * @Return AuthenticationInfo
	 * @Author WangShiLin
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
			return null;
		}
		//获取用户信息
		String userName = (String) authenticationToken.getPrincipal();
		User user = loginService.findUser(userName);
		if (user == null) {
			//这里返回后会报出对应异常
			return null;
		} else {
			//这里验证authenticationToken和simpleAuthenticationInfo的信息
			SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getUserPwd(), getName());
			return simpleAuthenticationInfo;
		}
	}
}
